#include "musiccollecteddao.h"
#include <QSqlQuery>
#include <QDebug>

MySqlMusicCollectedDao::MySqlMusicCollectedDao(const QString &host, const QString &dbName, 
                                               const QString &user, const QString &password)
    : hostName(host), databaseName(dbName), userName(user), password(password) {
    // 检查MySQL驱动
    if (!QSqlDatabase::isDriverAvailable("QMYSQL")) {
        errorMessage = "MySQL驱动不可用，请检查Qt配置";
        qDebug() << errorMessage;
    }
}

MySqlMusicCollectedDao::~MySqlMusicCollectedDao() {
    closeConnection();
}

bool MySqlMusicCollectedDao::openConnection() {
    if (isConnected()) {
        return true;
    }
    
    db = QSqlDatabase::addDatabase("QMYSQL", "MusicDBConnection");
    db.setHostName(hostName);
    db.setDatabaseName(databaseName);
    db.setUserName(userName);
    db.setPassword(password);
    
    if (!db.open()) {
        errorMessage = "数据库连接失败: " + db.lastError().text();
        qDebug() << errorMessage;
        return false;
    }
    
    return true;
}

void MySqlMusicCollectedDao::closeConnection() {
    if (db.isOpen()) {
        db.close();
    }
    QSqlDatabase::removeDatabase("MusicDBConnection");
}

bool MySqlMusicCollectedDao::isConnected() const {
    return db.isOpen();
}

QString MySqlMusicCollectedDao::lastError() const {
    return errorMessage;
}

bool MySqlMusicCollectedDao::addToCollection(const MusicInfo &music) {
    if (!isConnected()) {
        errorMessage = "数据库未连接";
        return false;
    }
    
    QSqlQuery query(db);
    query.prepare("INSERT INTO music_collected (music_id, title, singer, url) "
                  "VALUES (:music_id, :title, :singer, :url) "
                  "ON DUPLICATE KEY UPDATE is_collected = 1");
    query.bindValue(":music_id", music.id);
    query.bindValue(":title", music.title);
    query.bindValue(":singer", music.singer);
    query.bindValue(":url", music.url);
    
    if (!query.exec()) {
        errorMessage = "添加收藏失败: " + query.lastError().text();
        qDebug() << errorMessage;
        return false;
    }
    
    return true;
}

bool MySqlMusicCollectedDao::removeFromCollection(const QString &musicId) {
    if (!isConnected()) {
        errorMessage = "数据库未连接";
        return false;
    }
    
    QSqlQuery query(db);
    query.prepare("delete from music_collected WHERE music_id = :music_id");
    query.bindValue(":music_id", musicId);
    
    if (!query.exec()) {
        errorMessage = "移除收藏失败: " + query.lastError().text();
        qDebug() << errorMessage;
        return false;
    }
    
    return true;
}

bool MySqlMusicCollectedDao::updateCollectionStatus(const QString &musicId, bool isCollected) {
    if (!isConnected()) {
        errorMessage = "数据库未连接";
        return false;
    }
    
    QSqlQuery query(db);
    query.prepare("UPDATE music_collected SET is_collected = :status WHERE music_id = :music_id");
    query.bindValue(":status", isCollected ? 1 : 0);
    query.bindValue(":music_id", musicId);
    
    if (!query.exec()) {
        errorMessage = "更新收藏状态失败: " + query.lastError().text();
        qDebug() << errorMessage;
        return false;
    }
    
    return true;
}

bool MySqlMusicCollectedDao::isMusicCollected(const QString &musicId) const {
    if (!isConnected()) {
        const_cast<MySqlMusicCollectedDao*>(this)->errorMessage = "数据库未连接";
        return false;
    }
    
    QSqlQuery query(db);
    query.prepare("SELECT COUNT(*) FROM music_collected WHERE music_id = :music_id AND is_collected = 1");
    query.bindValue(":music_id", musicId);
    
    if (!query.exec() || !query.next()) {
        const_cast<MySqlMusicCollectedDao*>(this)->errorMessage = "查询收藏状态失败: " + query.lastError().text();
        return false;
    }
    
    return query.value(0).toInt() > 0;
}

QList<MusicInfo> MySqlMusicCollectedDao::getAllCollectedMusic() const {
    QList<MusicInfo> result;
    
    if (!isConnected()) {
        const_cast<MySqlMusicCollectedDao*>(this)->errorMessage = "数据库未连接";
        return result;
    }
    
    QSqlQuery query(db);
    query.prepare("SELECT music_id, title, singer, url FROM music_collected "
                  "WHERE is_collected = 1 ORDER BY collect_time DESC");
    
    if (!query.exec()) {
        const_cast<MySqlMusicCollectedDao*>(this)->errorMessage = "获取收藏列表失败: " + query.lastError().text();
        return result;
    }
    
    while (query.next()) {
        MusicInfo music;
        music.id = query.value("music_id").toString();
        music.title = query.value("title").toString();
        music.singer = query.value("singer").toString();
        music.url = query.value("url").toString();
        music.isCollected = true;
        result.append(music);
    }
    
    return result;
}

MusicInfo MySqlMusicCollectedDao::getMusicById(const QString &musicId) const {
    MusicInfo music;
    
    if (!isConnected()) {
        const_cast<MySqlMusicCollectedDao*>(this)->errorMessage = "数据库未连接";
        return music;
    }
    
    QSqlQuery query(db);
    query.prepare("SELECT music_id, title, singer, url, is_collected "
                  "FROM music_collected WHERE music_id = :music_id");
    query.bindValue(":music_id", musicId);
    
    if (!query.exec() || !query.next()) {
        const_cast<MySqlMusicCollectedDao*>(this)->errorMessage = "查询歌曲失败: " + query.lastError().text();
        return music;
    }
    
    music.id = query.value("music_id").toString();
    music.title = query.value("title").toString();
    music.singer = query.value("singer").toString();
    music.url = query.value("url").toString();
    music.isCollected = query.value("is_collected").toBool();
    
    return music;
}
